<?php

Plugin::setInfos(array(
	'id'		  	=> 'savemysql',
	'title'	   		=> 'SaveMySQL',
	'description' 		=> 'Provides compressed database backup during save/delete.',
	'version'		=> '0.4.0',
   	'license'	 	=> 'GPL',
	'author'	  	=> 'Steven Henderson',
	'website'		=> 'http://www.bluehorizonsmarketing.co.uk/',
	'update_url'		=> 'http://www.bluehorizonsmarketing.co.uk/plugins.xml',
	'require_framework_version'	=> '0.9.5'
));

if (strpos($_SERVER['PHP_SELF'], 'admin/index.php')) {

	//Plugin::addController('savemysql', 'SaveMySQL', 'administrator', false);

	Observer::observe('page_edit_after_save',	'sql_save');
	Observer::observe('page_add_after_save',	'sql_save');
	Observer::observe('page_delete',		'sql_save');

	Observer::observe('layout_after_delete',	'sql_save');
	Observer::observe('layout_after_edit',		'sql_save');
	
	Observer::observe('snippet_after_delete',	'sql_save');
	Observer::observe('snippet_after_edit',		'sql_save');
	
	Observer::observe('plugin_after_enable',	'sql_save');
	Observer::observe('plugin_after_disable',	'sql_save');

	function sql_save() {

		/* Settings */
		$compress = true;
		$compress_strength = '6';
		$backup_extension = 'dat';
		$tables = '*';

		preg_match("#dbname=(.*?);host=#",DB_DSN,$dbname);preg_match("#host=(.*?);port=#",DB_DSN,$host);
		
		$username = DB_USER;
		$password = DB_PASS;
		$database = $dbname[1];
		$localhost = $host[1];
		
		mysql_connect($localhost,$username,$password);
		@mysql_select_db($database) or die( "Unable to select database");

		if($tables == '*'){
			$tables = array();
			$result = mysql_query('SHOW TABLES');
			while($row = mysql_fetch_row($result)){
				$tables[] = $row[0];
			}
		} else {
			$tables = is_array($tables) ? $tables : explode(',',$tables);
		}

		foreach($tables as $table){
			$result = mysql_query('SELECT * FROM '.$table);
			$num_fields = mysql_num_fields($result);

			$return.= 'DROP TABLE '.$table.';';
			$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
			$return.= "\n\n".$row2[1].";\n\n";

			for ($i = 0; $i < $num_fields; $i++){
				while($row = mysql_fetch_row($result)){
					$return.= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$num_fields; $j++){
						$row[$j] = addslashes($row[$j]);
						$row[$j] = ereg_replace("\n","\\n",$row[$j]);
						if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
						if ($j<($num_fields-1)) { $return.= ','; }
					}
					$return.= ");\n";
				}
			}
			$return.="\n\n\n";
		}

		$file_date = date('Y-m-d H-i-s');
		$file_name = $file_date . '.' . $backup_extension;
		$backup_path = dirname(__FILE__) . '/backup/';
		$backup_file = $backup_path . $file_name;

		if($compress == true){
			compressfile($backup_file . '.gz', $return);
		} else {
			savefile($backup_file, $return);
		}

		mysql_close();

	}

	
	function restore(){
		/* Coming soon */;
	}
	
	function savefile($backup_file, $return){
		$fp = fopen($backup_file, 'w+');
		fwrite($fp, $return);
		fclose($fp);
	}

	function uncompressfile($backup_file){
		$filecontents = '';
		$ifh = gzopen($backup_file, 'r');
		while ($line = gzgets($ifh, 1024)){
		    $filecontents .= $line;
		}
		echo $filecontents;
		gzclose($ifh);
	}
	
	function compressfile($backup_file, $return){
		$filecontents = '';
		$ifh = gzopen($backup_file, 'r');
		while ($line = gzgets($ifh, 1024)){
			$filecontents .= $line;
		}
		gzclose($ifh);
		$ifh = gzopen($backup_file, 'w' . $compress_strength);
		if (!gzwrite($ifh, $filecontents.$return)){
			// write failed
		}
		gzclose($ifh);
	}

}